const state = {
	location: null, // { latitude, longitude }
	hasPermission: false
};

const mutations = {
	SET_LOCATION(state, payload) {
		state.location = payload;
	},
	SET_PERMISSION(state, payload) {
		state.hasPermission = payload;
	}
};

const actions = {
	async initLocation({ commit, dispatch }) {
		const cached = uni.getStorageSync('user_location');
		const isValid = cached && cached.latitude && cached.longitude;

		if (isValid) {
			commit('SET_LOCATION', cached);
			commit('SET_PERMISSION', true);
			return cached;
		}

		const hasAuth = await dispatch('checkPermission');
		if (hasAuth) {
			const location = await dispatch('getLocation');
			commit('SET_LOCATION', location);
			return location;
		} else {
			const granted = await dispatch('requestPermission');
			if (granted) {
				const location = await dispatch('getLocation');
				commit('SET_LOCATION', location);
				return location;
			} else {
				throw new Error('用户未授权模糊定位');
			}
		}
	},

	// ✅ 检查模糊定位权限
	checkPermission({ commit }) {
		return new Promise(resolve => {
			wx.getSetting({
				success(res) {
					const granted = res.authSetting['scope.userFuzzyLocation'];
					commit('SET_PERMISSION', granted);
					resolve(granted);
				},
				fail() {
					resolve(false);
				}
			});
		});
	},

	// ✅ 请求模糊定位权限
	requestPermission({ commit }) {
		return new Promise(resolve => {
			wx.authorize({
				scope: 'scope.userFuzzyLocation',
				success() {
					commit('SET_PERMISSION', true);
					resolve(true);
				},
				fail() {
					commit('SET_PERMISSION', false);
					resolve(false);
				}
			});
		});
	},

	// ✅ 使用 wx.getFuzzyLocation 获取定位
	getLocation({ commit }) {
		return new Promise((resolve, reject) => {
			wx.getFuzzyLocation({
				type: 'wgs84',
				success(res) {
					const location = {
						latitude: res.latitude,
						longitude: res.longitude
					};
					uni.setStorageSync('user_location', location);
					commit('SET_LOCATION', location);
					resolve(location);
				},
				fail(err) {
					console.error('定位失败', err);
					reject(err);
				}
			});
		});
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
};
